﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataAccess;
using DataAccess.Entities;
using Portal.Code;

namespace Portal
{
    public partial class Detail : BasePage
    {
        private int id;
        private int pageNum = Constant.DefaultPageNum;
        private int pageSize = Constant.DefaultPageSize;
        private int rank;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!int.TryParse(Request["Id"], out id) || id < 1)
                id = 1;

            if (IsPostBack) return;
            
            if (!int.TryParse(Request["pageNum"], out pageNum) || pageNum < 1)
                pageNum = Constant.DefaultPageNum;
            if (!int.TryParse(Request["PageSize"], out pageSize) || pageSize < 10)
                pageSize = Constant.DefaultPageSize;
            if (!int.TryParse(Request["Rank"], out rank) || rank < 1)
                rank = (new Random()).Next(1, 100);

            List<Comment> comments = null;
            int totalCount = 0;
            Organization org = null;
            using (var db = new CompanyDicContext())
            {
                org = db.Organizations.Where(p => p.Id == id).FirstOrDefault();
                comments = org.Comments.Skip((pageNum - 1) * pageSize).Take(pageSize).ToList();
                totalCount = db.Comments.Count(p => p.OrgId == id);

                litTitle.Text = org.Name;
                lblPageTitle.Text = org.Name;
                var sb = new StringBuilder();
                sb.AppendFormat("<span><a href=\"/\">首页</a></span>");
                sb.AppendFormat("<span> > </span>");
                sb.AppendFormat("<span><a href=\"/List.aspx?Category={0}\">{1}</a></span>", org.CategoryId, org.Category.Name);
                sb.AppendFormat("<span> > </span>");
                sb.AppendFormat("<span>{0}</span>", org.Name);
                litBreadcrumb.Text = sb.ToString();

                InitOrgDetailInfo(org);
                InitPageContent(comments);
            }

            var totalPageNum = int.Parse(decimal.Ceiling((decimal)totalCount / pageSize).ToString());
            Pagination pagination = PaginationHelper.GetPaginationInfo(totalPageNum, pageNum);
            InitPagination(pagination);
            TrackUser();
        }


        private void TrackUser()
        {
            using (var db = new CompanyDicContext())
            {
                db.UserTracks.Add(new UserTrack
                                      {
                                          OrgId = id,
                                          UserId = SessionManager.Instance.CurrentUserId,
                                          Ip = Request.ServerVariables["REMOTE_ADDR"].ToString(),
                                          CreateDate = DateTime.Now,
                                      });
                db.SaveChanges();
            }
        }


        private void InitPageContent(List<Comment> comments)
        {
            var sb = new StringBuilder();
            foreach (var comment in comments)
            {
                sb.AppendFormat("<li><div class=\"comment_title float_left\">");
                sb.AppendFormat("<div class=\"user_name float_left\">[{0}]</div>", comment.User.Name);
                sb.AppendFormat("<div class=\"submit_date float_left\">{0}</div>", comment.CreateDate);
                sb.AppendFormat("<a title=\"{0}分\">", comment.Mark);
                sb.AppendFormat("<ul class=\"mark_value float_right\">");
                for (int i = 0; i < comment.Mark && i < 5; i++)
                    sb.AppendFormat("<li class=\"mark_plus\"></li>");
                for (int i = comment.Mark; i < 5; i++)
                    sb.AppendFormat("<li class=\"mark_negative\"></li>");
                sb.AppendFormat("</ul></a></div>");
                sb.AppendFormat("<p class=\"comment_content\">{0}</p>", comment.Content);
            }
            litContent.Text = sb.ToString();
        }


        private void InitPagination(Pagination pagination)
        {
            if (!pagination.HasItems)
                return;
            var linkFormat = "Detail.aspx?Id={0}&PageSize={1}&PageNum={2}";
            var sb = new StringBuilder();
            sb.AppendFormat("<li><a href=\"{0}\"><</a></li>",
                            pagination.PrePageNum == pagination.CurPageNum
                                ? "#"
                                : string.Format(linkFormat, id, pageSize, pagination.PrePageNum));
            for (int i = pagination.StartPageNum; i <= pagination.EndPageNum; i++)
            {
                if (i == pagination.CurPageNum)
                {
                    sb.AppendFormat("<li><a class=\"selected\" href=\"#\">{0}</a></li>", i);
                }
                else
                {
                    sb.AppendFormat("<li><a href=\"{0}\">{1}</a></li>",
                                    string.Format(linkFormat, id, pageSize, i), i);
                }
            }
            sb.AppendFormat("<li><a href=\"{0}\">></a></li>",
                            pagination.NextPageNum == pagination.CurPageNum
                            ? "#" :
                            string.Format(linkFormat, id, pageSize, pagination.NextPageNum));

            litTopPagination.Text = sb.ToString();
            litBottomPagination.Text = sb.ToString();
        }


        private void InitOrgDetailInfo(Organization org)
        {
            lblRankValue.Text = rank.ToString();
            lblTotalMark.Text = org.TotalMark.ToString();
            lblArea.Text = org.Area == null ? "" : org.Area.Name;
            lblTel.Text = org.Tel;
            litSite.Text = string.Format("<a href=\"{0}\" target=\"_blank\">{0}</a>", org.Site);
            lblAddress.Text = org.Address;
            lblBrief.Text = org.OrgBrief == null ? "" : org.OrgBrief.Brief;
            using (var db = new CompanyDicContext())
            {
                var hotValue = db.UserTracks.Where(p => p.OrgId == org.Id).Count();
                lblHotValue.Text = hotValue.ToString();
            }
        }

        protected void btnSubmitComment_Click(object sender, EventArgs e)
        {
            using (var db = new CompanyDicContext())
            {
                int mark = int.Parse(hidMarkValue.Value);
                db.Comments.Add(new Comment()
                                    {
                                        Content = txtCommentContent.Text.Trim(),
                                        CreateBy = SessionManager.Instance.CurrentUserId,
                                        Mark = mark,
                                        CreateDate = DateTime.Now,
                                        OrgId = id,
                                    });

                db.Organizations.Where(p => p.Id == id).FirstOrDefault().TotalMark += mark;
                db.SaveChanges();
            }

            Response.Redirect(string.Format("/Detail.aspx?Id={0}&Rank={1}", id, rank));
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            Response.Redirect(string.Format("/OrgUpdate.aspx?Id={0}", id));
        }
    }
}